"""
应用设置模块：包含导入、日志、页面配置、样式和会话状态初始化。
"""
import os
import sys
import json
import datetime
from pathlib import Path
import logging

import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots

# 导入配置
try:
    from config.settings import SECTOR_ALLOCATION, SECTOR_NAME_MAP
except ImportError:
    SECTOR_ALLOCATION = {
        "tech": 0.3,
        "consumer": 0.2,
        "healthcare": 0.15,
        "finance": 0.15,
        "others": 0.2
    }
    SECTOR_NAME_MAP = {
        "tech": "科技",
        "consumer": "消费",
        "healthcare": "医疗",
        "finance": "金融",
        "others": "其他"
    }

# 将项目根目录添加到路径
# 注意：这里的路径可能需要根据实际运行 main.py 的位置调整
# 如果 main.py 在 web/ 目录下，则用 Path(__file__).parent.parent.parent
# 如果 main.py 在根目录，则用 Path(__file__).parent.parent
# 假设 main.py 在 web/ 目录下
project_root = str(Path(__file__).parent.parent.parent)
if project_root not in sys.path:
    sys.path.append(project_root)

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def setup_page():
    """设置 Streamlit 页面配置和样式"""
    st.set_page_config(
        page_title="A股投资智能体团队",
        page_icon="📈",
        layout="wide",
        initial_sidebar_state="expanded"
    )

    # 设置样式
    st.markdown("""
    <style>
        .main-header {
            font-size: 2.5rem;
            font-weight: bold;
            color: #1E3A8A;
            margin-bottom: 1rem;
        }
        .sub-header {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2563EB;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
        }
        .info-text {
            font-size: 1rem;
            color: #4B5563;
        }
        .highlight {
            background-color: #DBEAFE;
            padding: 0.5rem;
            border-radius: 0.3rem;
        }
        .stock-up {
            color: #EF4444; /* A股红涨 */
        }
        .stock-down {
            color: #10B981; /* A股绿跌 */
        }
    </style>
    """, unsafe_allow_html=True)

def initialize_session_state():
    """初始化基本的会话状态变量"""
    if 'run_id' not in st.session_state:
        st.session_state.run_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    if 'data_loaded' not in st.session_state:
        st.session_state.data_loaded = False
    if 'workflow_result' not in st.session_state:
        st.session_state.workflow_result = {
            "market_analysis": {
                "summary": "默认市场观点：市场震荡，关注科技和消费行业",
                "market_trend": "neutral",
                "sector_rotation": SECTOR_ALLOCATION,
                "sector_names": SECTOR_NAME_MAP
            },
            "portfolio_allocation": {
                "stocks": 0.7,
                "bonds": 0.2,
                "cash": 0.1,
                "sectors": SECTOR_ALLOCATION
            },
            "stock_picks": ["600519", "000858", "600036"]
        }
    if 'selected_tab' not in st.session_state:
        st.session_state.selected_tab = "市场概览" # 默认标签页
    # data_collector, indices_data, stock_data 的初始化将移至 data_collector 模块